/**
 * 	Main.java
 *
 *  This file is part of the PDFGen Syllabus Formatter Project.
 *  Copyright (C) 2011  Gian Fontanilla
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.dlsu.pdfgen;

import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.dlsu.pdfgen.exceptions.InvalidXMLFileFormatException;
import org.dlsu.pdfgen.io.XMLReader;
import org.dlsu.pdfgen.struct.Syllabus;

import com.itextpdf.text.DocumentException;

/**
 * The main class.
 *
 * @author pckid
 * @version 0.04a
 * @see Formatter
 */
public class Main {

	/**
	 * The main method.
	 *
	 * @param args
	 *            Array of arguments. First argument is the name of the input
	 *            XML file (required). Second argument is the name of the output
	 *            PDF file (optional).
	 */
	public static void main(String[] args) {

		Formatter f = null;
		Syllabus s = new Syllabus();
		boolean success = false;
		final String usage = "Usage: java -jar syllabus-formatter-<version number>.jar <inputfile>.xml [ <outputfile> ].pdf";

		if (args.length > 0) {
			// Command-line with arguments
			if (args[0].equalsIgnoreCase("-h") || args[0].equalsIgnoreCase("?")) {
				System.out.println(usage);
			} else {
				try {
					s = XMLReader.getInstance().readSyllabus(args[0]);
					if (args.length > 1)
						f = new Formatter(s, args[1]);
					else
						f = new Formatter(s);
					success = true;
				} catch (FileNotFoundException e) {
					System.out.println("File not Found: " + e.getMessage());
				} catch (DocumentException e) {
					System.out.println("Document error: " + e.getMessage());
				} catch (InvalidXMLFileFormatException e) {
					System.out.println("XML read error: " + e.getMessage());
				}
			}

		} else {
			// GUI
			java.awt.EventQueue.invokeLater(new Runnable() {
				public void run() {
					System.out.println("Starting GUI...");
					new Controller();

				}
			});
		}

		if (success) {
			try {
				Controller.openPDF(f.outputFileName);
				System.out.println("Generated file: " + f.outputFileName);
			} catch (IOException e) {
				System.out.println("IO Error: " + e.getMessage());
			}
		} else
			System.out
					.println("No files were generated from command line arguments.");
		// System.out.println("End of Program");
	}

}
